package com.zhiyinlou.apps.utils.sendRequest;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.alibaba.fastjson.JSONObject;
import com.zhiyinlou.apps.utils.sql.tresult.RequestStatusDbTest;


public class SendRequestUtils {

	
	public static Logger logger = LogManager.getLogger(SendRequestUtils.class);
	private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static SimpleDateFormat mdf = new SimpleDateFormat("yyyy-MM-dd-HH-mm");

	// 普通get请求
	public static String httpCommonGet(String url, HashMap<String, String> requsetHeaders){

		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpGet httpGet = new HttpGet();
		try {
			httpGet.setURI(new URI(url));

			for (Entry<String, String> entry : requsetHeaders.entrySet()) {
				httpGet.setHeader(entry.getKey(), entry.getValue());
			}
			double startTime = System.currentTimeMillis();
			response = httpClient.execute(httpGet);
			double endTime = System.currentTimeMillis();
			// 如果server端返回http 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;		
				RequestStatusDbTest.insert_result(url, code, "success", String.valueOf(time));
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				logger.error("请求失败 : " + response.getStatusLine().getReasonPhrase());
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;
				RequestStatusDbTest.insert_result(url, code, "error", String.valueOf(time));
				return "请求失败:"+code;
			}
		}catch(Exception e) {
			RequestStatusDbTest.insert_result(url, "不可能出现", "不可能出现","不可能出现");
			return "不可能出现";
		}


	}

	// 普通post请求
	public static String httpCommonPost(String url, HashMap<String, String> requsetHeaders,
			HashMap<String, String> requsetParams) {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(url);
		List<NameValuePair> params = new ArrayList<NameValuePair>();

		for (Entry<String, String> entry : requsetHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
		if (null != requsetParams) {
			// 对request中的value转换
			Iterator<Entry<String, String>> requestIte = requsetParams.entrySet().iterator();

			while (requestIte.hasNext()) {
				Map.Entry<String, String> requestEntry = requestIte.next();
				requestEntry.setValue(requestEntry.getValue());
			}

			Set<String> keys = requsetParams.keySet();

			for (String key : keys) {
				params.add(new BasicNameValuePair(key, requsetParams.get(key)));
			}
		}
		
		try {
			if (null != requsetParams) {
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(params, "utf-8");
				httpPost.setEntity(entity);
			}
			double startTime = System.currentTimeMillis();
			response = httpClient.execute(httpPost);
			double endTime = System.currentTimeMillis();

			// 如果server端返回http 200
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;		
				RequestStatusDbTest.insert_result(url, code, "success", String.valueOf(time));
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				logger.error("请求失败 : " + response.getStatusLine().getReasonPhrase());
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;
				RequestStatusDbTest.insert_result(url, code, "error", String.valueOf(time));
				return "请求失败:"+code;
			}
		}catch(Exception e) {
			RequestStatusDbTest.insert_result(url, "不可能出现", "不可能出现","不可能出现");
			return "不可能出现";
		}

		

	}

	// post json数据
	public static String httpJsonPost(String url, HashMap<String, String> requsetHeaders, JSONObject jsonObj){
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(url);

		for (Entry<String, String> entry : requsetHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}
		
		try {
			StringEntity strEntity = new StringEntity(jsonObj.toJSONString(),"utf-8");
			System.out.println(jsonObj.toJSONString());
			strEntity.setContentEncoding("UTF-8");
			strEntity.setContentType("application/json");
			httpPost.setEntity(strEntity);
			
			double startTime = System.currentTimeMillis();
			response = httpClient.execute(httpPost);
			double endTime = System.currentTimeMillis();

			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;		
				RequestStatusDbTest.insert_result(url, code, "success", String.valueOf(time));
				
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				logger.error("请求失败 : " + response.getStatusLine().getReasonPhrase());
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;
				RequestStatusDbTest.insert_result(url, code, "error", String.valueOf(time));
				return "请求失败:"+code;
			}
			
		}catch(Exception e) {
			RequestStatusDbTest.insert_result(url, "不可能出现", "不可能出现","不可能出现");
			return "不可能出现";
		}
		

	}

	/**
	 * MultipartEntityBuilder 使用用法 第一步：首先是设置上传的模式；
	 * setMode(HttpMultipartModemode)，其中mode主要有BROWSER_COMPATIBLE，RFC6532，STRICT三种，默认值是STRICT。
	 * 第二步：其次是创建MultipartEntityBuilder对象，并添加需要上传的数据；
	 * a.利用MultipartEntityBuilder.create()来创建对象；
	 * b.addBinaryBody：以二进制的形式添加数据，可以添加File、InputStream、byte[]类型的数据。
	 * addBinaryBody(String name, File file, ContentType contentType, String
	 * filename) addBinaryBody(String name, InputStream stream, ContentType
	 * contentType, String filename) addBinaryBody(String name, byte[] b,ContentType
	 * contentType, String filename) c.addTextBody：添加文本数据addTextBody(String name,
	 * String text, ContentType contentType)
	 * d.addPart：以Key/Value的形式添加ContentBody类型的数据 addPart(String name,
	 * ContentBodycontentBody)
	 * 
	 * @param url
	 * @param requsetHeaders
	 * @param requsetBody
	 * @param listfilefolderpath
	 * @return
	 * @throws IOException
	 * @throws ClientProtocolException
	 * @throws WriteException
	 * @throws BiffException
	 * @throws RowsExceededException
	 */

	public static String httpFilePost(String url, HashMap<String, String> requestHeaders,
			HashMap<String, String> requestBody, HashMap<String, File> requestBody2) {
		
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(url);

		for (Entry<String, String> entry : requestHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		for (Entry<String, String> entry : requestBody.entrySet()) {
			builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN);
		}
		for (Entry<String, File> entry : requestBody2.entrySet()) {
			builder.addBinaryBody(entry.getKey(), entry.getValue());
		}

		HttpEntity multipart = builder.build();
		httpPost.setEntity(multipart);
		
		try {
			double startTime = System.currentTimeMillis();
			response = httpClient.execute(httpPost);
			double endTime = System.currentTimeMillis();
			if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				HttpEntity responseEntity = response.getEntity();
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;		
				RequestStatusDbTest.insert_result(url, code, "success", String.valueOf(time));
				return EntityUtils.toString(responseEntity, "UTF-8");
			} else {
				logger.error("请求失败 : " + response.getStatusLine().getReasonPhrase());
				String code = String.valueOf(response.getStatusLine().getStatusCode());
				double time = endTime - startTime;
				RequestStatusDbTest.insert_result(url, code, "error", String.valueOf(time));
				return "请求失败:"+code;
			}
		}catch(Exception e) {
			RequestStatusDbTest.insert_result(url, "不可能出现", "不可能出现","不可能出现");
			return "不可能出现";
		}	
	}

	public static String httpBatchFilePost(String url, HashMap<String, String> requestHeaders,
			HashMap<String, String> requestBody, List<File> listfilefolderpath, HashMap<String, ArrayList> requestBody3)
			throws ClientProtocolException, IOException {
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		HttpPost httpPost = new HttpPost(url);

		for (Entry<String, String> entry : requestHeaders.entrySet()) {
			httpPost.setHeader(entry.getKey(), entry.getValue());
		}

		MultipartEntityBuilder builder = MultipartEntityBuilder.create();
		for (Entry<String, String> entry : requestBody.entrySet()) {
			builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.TEXT_PLAIN);
		}
		for (int i = 0; i < listfilefolderpath.size(); i++) {
			String strfilename_temp = listfilefolderpath.get(i).getName();
			String strjpgfilename = listfilefolderpath.get(i).getParent() + File.separator + strfilename_temp;
			File f = new File(strjpgfilename);
			builder.addBinaryBody("file" + i, f);
		}
		for (Entry<String, ArrayList> entry : requestBody3.entrySet()) {
			builder.addTextBody(entry.getKey(), entry.getValue().toString(), ContentType.TEXT_PLAIN);
		}

		HttpEntity multipart = builder.build();
		httpPost.setEntity(multipart);

		response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity responseEntity = response.getEntity();
			return EntityUtils.toString(responseEntity, "UTF-8");
		} else {
			logger.error("请求失败 : " + response.getStatusLine().getReasonPhrase());
			return null;
		}

	}

	
}
